/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package SMC.PresentationLayer;

import SMC.BussinesObjects.Agente_Vendedor_DML;
import SMC.DataAccessLayer.ConectarBaseDeDatos;
import SMC.BussinesObjects.Excepciones;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author SATELLITE
 */
public final class Agente_Vendedor extends javax.swing.JFrame {

    private DefaultTableModel model;
    private final Connection con = ConectarBaseDeDatos.getConnect();

    public enum Tipo {

        EDITAR, NUEVO
    }

    /**
     * Creates new form Agente_Vendedor
     */
    public Agente_Vendedor() {
        initComponents();
        llenarTabla();
        btnEditar.setEnabled(false);
        jcbColumnas.setModel(mjcb);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblAgentes = new javax.swing.JTable();
        btnAgregar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        btnEditar = new javax.swing.JButton();
        jcbColumnas = new javax.swing.JComboBox();
        txtBuscar = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tblAgentes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tblAgentes.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        tblAgentes.getTableHeader().setReorderingAllowed(false);
        tblAgentes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblAgentesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblAgentes);

        btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SMC/images/add.png"))); // NOI18N
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SMC/images/remove.png"))); // NOI18N
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SMC/images/Agent Menu.png"))); // NOI18N

        jLabel1.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
        jLabel1.setText("Agentes Vendedores");

        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SMC/images/edit.png"))); // NOI18N
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        jcbColumnas.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jcbColumnasItemStateChanged(evt);
            }
        });

        txtBuscar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBuscarKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(139, 139, 139)
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(75, 75, 75)
                .addComponent(jcbColumnas, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(btnAgregar, javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(btnEliminar, javax.swing.GroupLayout.Alignment.TRAILING))
                    .addComponent(btnEditar))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 933, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jcbColumnas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(9, 9, 9)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 367, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(45, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents
    public static Tipo tipo_ventana;
    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        // TODO add your handling code here:
        tipo_ventana = Tipo.NUEVO;

        JFrame ventana = new Nuevo_Agente_Vendedor(this);
        ventana.show();
        ventana.setLocationRelativeTo(null);


    }//GEN-LAST:event_btnAgregarActionPerformed

    
    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        // TODO add your handling code here:

        if (JOptionPane.showConfirmDialog(null, "¿Está seguro?", "WARNING",
                JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
            try {
                // model.removeRow(tblAgentes.getSelectedRow());
                removeSelectedRows(tblAgentes);
            } catch (SQLException ex) {
               JOptionPane.showMessageDialog(rootPane,
                                             Excepciones.Excepciones(ex.getErrorCode())+" "+Agente_Vendedor_DML.getCi());
            }

        }


    }//GEN-LAST:event_btnEliminarActionPerformed

    public void removeSelectedRows(JTable table) throws SQLException {
        table.getModel();
        int[] rows = table.getSelectedRows();

        CallableStatement stmt;
        for (int i = 0; i < rows.length; i++) {
            Object selectedObject = (Object) tblAgentes.getValueAt(fila, 0);
            String sql = "{CALL DELETE_AGENTE_POR_CI('" + selectedObject + "')}";
            stmt = con.prepareCall(sql);
            stmt.execute();
            model.removeRow(rows[i] - i);
        }

    }
    int fila, columna;

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        // TODO add your handling code here:
        int[] rows = tblAgentes.getSelectedRows();

        if (rows.length == 1) {
            tipo_ventana = Tipo.EDITAR;
            JFrame ventana = new Nuevo_Agente_Vendedor(this);
            ventana.setLocationRelativeTo(null);
            ventana.show();
        } else {
            JOptionPane.showMessageDialog(rootPane, "Debe elegir solo una fila a editar", "Atención", JOptionPane.ERROR_MESSAGE);
        }


    }//GEN-LAST:event_btnEditarActionPerformed

    private void tblAgentesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblAgentesMouseClicked
        // TODO add your handling code here:
        btnEditar.setEnabled(true);
        fila = tblAgentes.rowAtPoint(evt.getPoint());
        columna = tblAgentes.columnAtPoint(evt.getPoint());

        System.err.println(evt.getPoint());

        Agente_Vendedor_DML.setCi(tblAgentes.getValueAt(fila, 0).toString());
        Agente_Vendedor_DML.setApellido_paterno(tblAgentes.getValueAt(fila, 1).toString());
        Agente_Vendedor_DML.setApellido_materno(tblAgentes.getValueAt(fila, 2).toString());
        Agente_Vendedor_DML.setNombre1(tblAgentes.getValueAt(fila, 3).toString());
        Agente_Vendedor_DML.setNombre2(tblAgentes.getValueAt(fila, 4).toString());
        Agente_Vendedor_DML.setDirección(tblAgentes.getValueAt(fila, 5).toString());
        Agente_Vendedor_DML.setTeléfono(tblAgentes.getValueAt(fila, 6).toString());

    }//GEN-LAST:event_tblAgentesMouseClicked

    String[] titulos_combo = {"CI", "APELLIDO PATERNO", "APELLIDO MATERNO", "NOMBRE 1", "NOMBRE 2", "DIRECCIÓN", "TELÉFONO"};
    DefaultComboBoxModel mjcb = new DefaultComboBoxModel(titulos_combo);
            
    private void jcbColumnasItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jcbColumnasItemStateChanged
        // TODO add your handling code here:
       
                
    }//GEN-LAST:event_jcbColumnasItemStateChanged

    private void txtBuscarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarKeyReleased
        // TODO add your handling code here:
        // TODO add your handling code here:

        try {
            String[] titulos = {"CEDULA", "APELLIDO PATERNO", "APELLIDO MATERNO", "NOMBRE 1", "NOMBRE 2", "DIRECCIÓN", "TELÉFONO"};
            
            String[] registros = new String[7];
            model = new DefaultTableModel(null, titulos);
            
            
            String sql = "SELECT * FROM AGENTE_VENDEDOR WHERE`agente_vendedor`.`" + jcbColumnas.getSelectedItem() + "` LIKE '" + txtBuscar.getText() + "%'";
            
            CallableStatement stmt = con.prepareCall(sql);
            ResultSet rs = stmt.executeQuery();
              //JOptionPane.showMessageDialog(rootPane, sql);
            while (rs.next()) {
                registros[0] = rs.getString("CI");
                registros[1] = rs.getString("APELLIDO PATERNO");
                registros[2] = rs.getString("APELLIDO MATERNO");
                registros[3] = rs.getString("NOMBRE 1");
                registros[4] = rs.getString("NOMBRE 2");
                registros[5] = rs.getString("DIRECCIÓN");
                registros[6] = rs.getString("TELÉFONO");
                model.addRow(registros);
            }
            tblAgentes.setModel(model);
         
            
            
           

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(rootPane, ex.getCause());
            
        }
    }//GEN-LAST:event_txtBuscarKeyReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Agente_Vendedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Agente_Vendedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Agente_Vendedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Agente_Vendedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Agente_Vendedor().setVisible(true);

            }
        });
    }

    public void llenarTabla() {
        try {
            String[] titulos = {"CEDULA", "APELLIDO PATERNO", "APELLIDO MATERNO", "NOMBRE 1", "NOMBRE 2", "DIRECCIÓN", "TELÉFONO"};
            String[] registros = new String[7];
            model = new DefaultTableModel(null, titulos);

            String sql = "{CALL SELECT_AGENTE()}";
            CallableStatement stmt = con.prepareCall(sql);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                registros[0] = rs.getString("CI");
                registros[1] = rs.getString("APELLIDO PATERNO");
                registros[2] = rs.getString("APELLIDO MATERNO");
                registros[3] = rs.getString("NOMBRE 1");
                registros[4] = rs.getString("NOMBRE 2");
                registros[5] = rs.getString("DIRECCIÓN");
                registros[6] = rs.getString("TELÉFONO");
                model.addRow(registros);
            }
            tblAgentes.setModel(model);

        } catch (SQLException ex) {
            System.err.println("Error " + ex);
        }
    }

    ////////////////////TEST*//*/*

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JComboBox jcbColumnas;
    private javax.swing.JTable tblAgentes;
    private javax.swing.JTextField txtBuscar;
    // End of variables declaration//GEN-END:variables
}
